<template>
    <section class="grid-table" :class="{
        border: border
    }">
        <slot>
            <grid-table-row>
                <grid-table-cell isHead v-for="(th, index) of columns" :width="th.width" :colspan="th.colspan">
                    <slot name="headerCell" :title="th.title" :column="th">
                        {{ th?.title ?? th }}
                    </slot>
                </grid-table-cell>
            </grid-table-row>

            <grid-table-row v-for="(row, rowindex) of dataSource">
                <grid-table-cell v-for="th of columns">
                    <slot name="bodyCell" :index="rowindex" :record="row" :column="th">
                        {{ getValueByModel(th.dataIndex, row) }}
                    </slot>
                </grid-table-cell>
            </grid-table-row>
        </slot>
    </section>
</template>

<script lang="ts" setup>
import { provide, ref } from "vue"
import { TABLE_PROVIDE_KEY, use_TABLE_CONFIG } from "./index"
defineProps({
    border: {
        type: Boolean,
        default: true
    },
    columns: {
        type: Array,
        default: () => []
    },
    dataSource: {
        type: Array,
        default: () => []
    },
})
const TABLE_CONFIG = use_TABLE_CONFIG()
provide(TABLE_PROVIDE_KEY, TABLE_CONFIG)

function getValueByModel(dataIndex: string| string[], data: any): any {

    if(!data) return data;

    if (Array.isArray(dataIndex) && dataIndex.length === 1) {
    return data[dataIndex[0]];
    } else if(Array.isArray(dataIndex)){
    let key = dataIndex[0];
    return getValueByModel(dataIndex.slice(1), data[key]);
    }
    else{
        return data[dataIndex];
    }
}
</script>

<style lang="less" scoped>
.grid-table{
    color: #333;
    font-size: 14px;
    line-height: 1.5;
    overflow-x: auto;
}
</style>